package com.takwolf.libgdx.room;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.math.Rectangle;
import com.takwolf.libgdx.core.Game;
import com.takwolf.libgdx.core.Room;
import com.takwolf.libgdx.graphics.FontSheet;
import com.takwolf.libgdx.graphics.GLUtils;
import com.takwolf.libgdx.graphics.SpriteSheet;
import com.takwolf.libgdx.tiled.TiledMap;

public class LogoRoom extends Room {

    private Texture texFont;
    private Texture texPlayer;
    private FontSheet fontSheet;
    private SpriteSheet animPlayer;
    private Music music;

    private Texture texCtrl;
    private Texture texCtrl2;


    private float x;
    private float y;

    private TiledMap map;

    public LogoRoom(Game game) {
        super(game);
    }

    @Override
    protected void show() {
        texCtrl = getGame().getAsset().loadTexture("controller.png");
        texCtrl2 = getGame().getAsset().loadTexture("controller2.png");

        texFont = getGame().getAsset().loadTexture("font.png");
        texPlayer = getGame().getAsset().loadTexture("player.png");
        fontSheet = new FontSheet(texFont);
        animPlayer = SpriteSheet.create(0.05f, texPlayer, 10, 1, Animation.PlayMode.LOOP);

        x = getGame().getViewport().getWidth() / 2.0f;
        y = 7 * 16 + 2;

        music = getGame().getAsset().loadMusic("bgm.mp3");
        music.setLooping(true);
        music.play();

        map = getGame().getAsset().loadTiledMap(Gdx.files.internal("map_1.json"));
    }

    @Override
    protected void update() {
        x += Gdx.input.getAccelerometerY() / (Math.abs(Gdx.input.getAccelerometerY()) + 0.1);
        y -= Gdx.input.getAccelerometerX() / (Math.abs(Gdx.input.getAccelerometerX()) + 0.1);
        animPlayer.setCenter(x, y);
        animPlayer.update(getGame().getStateTime());
    }

    @Override
    protected void draw(Batch batch) {
        GLUtils.clear(0, 0, 0, 1);
        batch.begin();

        // 场景绘制开始-摄像机焦点为玩家
        getGame().getViewport().setCameraTarget(batch, x, y);

        map.drawViewport(batch, getGame().getViewport(), true);

        animPlayer.draw(batch);

        // UI绘制开始-摄像机焦点为屏幕中心
        getGame().getViewport().setCameraTargetToScreenCenter(batch);

        if (!Gdx.input.isTouched()) {
            batch.draw(texCtrl, 8, 8);
        } else {
            batch.draw(texCtrl2, 8, 8);
        }

        // 显示FPS
        fontSheet.draw(batch, "FPS:" + (1 + (int) (1 / getGame().getDeltaTime())), fontSheet.getCharWidth(), getGame().getViewport().getHeight() - fontSheet.getCharHeight());

        batch.end();
    }

    @Override
    protected void hide() {

    }

}
